package com.luke.web.controller.base;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.luke.base.domain.*;
import com.luke.base.service.*;
import com.luke.common.config.LuKeConfig;
import com.luke.common.core.controller.BaseController;
import com.luke.common.core.domain.AjaxResult;
import com.luke.common.core.domain.entity.SysDictData;
import com.luke.common.core.domain.entity.SysUser;
import com.luke.common.core.domain.model.LoginUser;
import com.luke.common.core.redis.RedisCache;
import com.luke.common.exception.BaseException;
import com.luke.common.utils.DateUtils;
import com.luke.common.utils.SecurityUtils;
import com.luke.common.utils.StringUtils;
import com.luke.common.utils.file.FileUploadUtils;
import com.luke.framework.web.service.TokenService;
import com.luke.system.domain.SysNotice;
import com.luke.system.service.ISysDictTypeService;
import com.luke.system.service.ISysNoticeService;
import com.luke.web.controller.base.bo.AccountBo;
import com.luke.web.controller.base.bo.EquipmentBo;
import com.luke.web.controller.base.bo.LoginBody;
import com.luke.web.controller.base.bo.UserBo;
import com.luke.web.controller.util.ALiSmsUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 
 * @author luke
 */
@Api("系统接口")
@RestController
@RequestMapping("/sysApi")
public class SysApiController extends BaseController
{
    @Autowired
    private ILkUserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ILkEquipmentService equipmentService;
    @Autowired
    private ILkConfigService configService;
    @Autowired
    private ILkVehicleService vehicleService;
    @Autowired
    private ILkQuestionService lkQuestionService;
    @Autowired
    private ILkProblemService lkProblemService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IRetrieveAlarmService retrieveAlarmService;
    @Autowired
    private ISysNoticeService noticeService;



    @ApiOperation("获取手机验证码")
    @GetMapping("/verificationCode")
    public AjaxResult verificationCode(String phonenumber)
    {
        int code = (int)((Math.random()*9+1)*100000);
        SendSmsResponse response=ALiSmsUtil.sendSms(phonenumber,code+"");
        //如果发送成功
        if("OK".equals(response.getCode())){
            //将验证码放入redis
            redisCache.setCacheObject(phonenumber,code+"",5, TimeUnit.MINUTES);
            return AjaxResult.success("短信发送成功");
        }else {
            return AjaxResult.error("短信发送失败");
        }
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody UserBo userBo)
    {
        //获取缓存中的验证码
        String code=redisCache.getCacheObject(userBo.getPhonenumber());
        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("验证码过期,请重新获取");
        }
        //验证码是否正确
        if (!code.equals(userBo.getCode())){
            return AjaxResult.error("验证码错误");
        }else {
            //验证成功后从缓存中删除
            redisCache.deleteObject(userBo.getPhonenumber());
        }
        //手机号是否唯一
        LkUser q=new LkUser();
        q.setPhonenumber(userBo.getPhonenumber());
        List<LkUser> userList=userService.selectLkUserList(q);
        if(userList.size()>0){
            return AjaxResult.error("该手机号已被注册");
        }
        LkUser lkUser=new LkUser();
        lkUser.setPhonenumber(userBo.getPhonenumber());
        lkUser.setDeviceNumber(userBo.getDeviceNumber());
        lkUser.setAddress(userBo.getAddress());
        lkUser.setPassword(SecurityUtils.encryptPassword(userBo.getPassword()));
        lkUser.setBirthday(userBo.getBirthday());
        lkUser.setNickName(userBo.getNickName());
        lkUser.setSex(userBo.getSex());
        lkUser.setParentId(0L);
        lkUser.setDelStatus(0);
        lkUser.setCreateTime(new Date());
        return toAjax(userService.insertLkUser(lkUser));
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        LkUser user = userService.selectUserByPhonenumber(loginBody.getPhonenumber());
        if (StringUtils.isNull(user)){
            throw new BaseException("用户不存在");
        }else if (!SecurityUtils.matchesPassword(loginBody.getPassword(), user.getPassword())){
            throw new BaseException("密码不正确");
        }
        //生成令牌
        AjaxResult ajax = AjaxResult.success();
        LoginUser loginUser=new LoginUser();
        SysUser sysUser=new SysUser();
        sysUser.setUserId(user.getUserId());
        loginUser.setUser(sysUser);
        String token=tokenService.createToken(loginUser);
        ajax.put("data",token);
        return ajax;
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo()
    {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        return AjaxResult.success(userService.selectLkUserById(userId));
    }

    @ApiOperation("添加驾驶员")
    @PostMapping("/addDriver")
    public AjaxResult addDriver(@RequestBody UserBo userBo)
    {
        //获取缓存中的验证码
        String code=redisCache.getCacheObject(userBo.getPhonenumber());
        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("验证码过期,请重新获取");
        }
        //验证码是否正确
        if (!code.equals(userBo.getCode())){
            return AjaxResult.error("验证码错误");
        }else {
            //验证成功后从缓存中删除
            redisCache.deleteObject(userBo.getPhonenumber());
        }
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        //手机号是否唯一
        LkUser q=new LkUser();
        q.setPhonenumber(userBo.getPhonenumber());
        List<LkUser> userList=userService.selectLkUserList(q);
        if(userList.size()>0){
            return AjaxResult.error("该手机号已被注册");
        }
        LkUser lkUser=new LkUser();
        lkUser.setPhonenumber(userBo.getPhonenumber());
        lkUser.setDeviceNumber(userBo.getDeviceNumber());
        lkUser.setAddress(userBo.getAddress());
        lkUser.setPassword(SecurityUtils.encryptPassword(userBo.getPassword()));
        lkUser.setBirthday(userBo.getBirthday());
        lkUser.setNickName(userBo.getNickName());
        lkUser.setSex(userBo.getSex());
        lkUser.setParentId(userId);
        lkUser.setDelStatus(0);
        lkUser.setCreateTime(new Date());
        return toAjax(userService.insertLkUser(lkUser));
    }

    @ApiOperation("查询驾驶员信息")
    @GetMapping("/getDriver")
    public AjaxResult getDriver()
    {
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        LkUser user=userService.selectLkUserByParentId(userId);
        return AjaxResult.success(user);
    }

    @ApiOperation("删除驾驶员")
    @PostMapping("/deleteDriver")
    public AjaxResult deleteDriver()
    {
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        LkUser user=userService.selectLkUserByParentId(userId);
        return toAjax(userService.deleteLkUserById(user.getUserId()));
    }

    @ApiOperation("查询设备信息")
    @GetMapping("/getEquipment")
    public AjaxResult getEquipment(String equipmentNumber)
    {
        return AjaxResult.success(equipmentService.selectLkEquipmentByNumber(equipmentNumber));
    }

    /**
     * 设备绑定用户
     */
    @ApiOperation("绑定车辆")
    @PostMapping("/bindEquipment")
    public AjaxResult bindEquipment(@RequestBody EquipmentBo equipmentBo)
    {
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        LkEquipment lkEquipment=equipmentService.selectLkEquipmentById(equipmentBo.getId());
        lkEquipment.setBatteryType(equipmentBo.getBatteryType());
        lkEquipment.setBatteryVoltage(equipmentBo.getBatteryVoltage());
        lkEquipment.setUserId(userId);
        return toAjax(equipmentService.updateLkEquipment(lkEquipment));
    }

    /**
     * 设备解除绑定
     */
    @ApiOperation("解除车辆绑定")
    @PostMapping("/unbindEquipment")
    public AjaxResult unbindEquipment(String equipmentNumber)
    {
        LkEquipment equipment=equipmentService.selectLkEquipmentByNumber(equipmentNumber);
        equipment.setUserId(null);
        return toAjax(equipmentService.updateLkEquipment(equipment));
    }

    /**
     * 查询系统信息
     */
    @ApiOperation("查询系统信息")
    @GetMapping("/getSysInfo")
    public AjaxResult getSysInfo()
    {
        return AjaxResult.success(configService.selectLkConfigById(1));
    }

    /**
     * 查询车型列表
     */
    @ApiOperation("查询车型列表")
    @GetMapping("/getVehicleList")
    public AjaxResult getVehicleList()
    {
        List<LkVehicle> vehicleList=vehicleService.selectLkVehicleList(new LkVehicle());
        return AjaxResult.success(vehicleList);
    }
    /**
     * 查询车型详情
     */
    @ApiOperation("查询车型详情")
    @GetMapping("/getVehicleById")
    public AjaxResult getVehicleList(Long id)
    {
        return AjaxResult.success(vehicleService.selectLkVehicleById(id));
    }

    /**
     * 查询我绑定的车辆(驾驶员也可查)
     */
    @ApiOperation("查询我绑定的车辆(驾驶员也可查)")
    @GetMapping("/getMyEquipment")
    public AjaxResult getMyEquipment()
    {
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        //查询用户信息
        LkUser user=userService.selectLkUserById(userId);
        if(user.getParentId().longValue()!=0){
            userId=user.getParentId();
        }
        LkEquipment q=new LkEquipment();
        q.setUserId(userId);
        List<LkEquipment> equipmentList=equipmentService.selectLkEquipmentList(q);
        return AjaxResult.success(equipmentList);
    }
    /**
     * 在线问答
     */
    @ApiOperation("在线问答")
    @GetMapping("/onlineQuestion")
    public AjaxResult onlineQuestion()
    {
        List<LkQuestion> questions=lkQuestionService.selectLkQuestionList(new LkQuestion());
        return AjaxResult.success(questions);
    }
    /**
     * 添加问题反馈
     */
    @ApiOperation("添加问题反馈")
    @PostMapping(value = "/addProblem",consumes = "multipart/form-data",headers = "content-type=multipart/form-data")
    public AjaxResult addProblem(
            @ApiParam(value = "车辆型号", required = true)@RequestParam("vehicleModel")String vehicleModel,
            @ApiParam(value = "问题标题", required = true)@RequestParam("problemTitle")String problemTitle,
            @ApiParam(value = "问题内容", required = true)@RequestParam("problemContent")String problemContent,
            @ApiParam(value = "问题图片", required = true)@RequestParam("images")MultipartFile[] images ) throws IOException {
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        //文件上传
        String problemImg="";
        for (MultipartFile image : images) {
            if (!image.isEmpty())
            {
                String avatar = FileUploadUtils.upload(LuKeConfig.getProblemPath(), image);
                if(StringUtils.isBlank(problemImg)){
                    problemImg=avatar;
                }else {
                    problemImg=problemImg+","+avatar;
                }
            }
        }
        LkProblem problem=new LkProblem();
        problem.setProblemTitle(problemTitle);
        problem.setProblemContent(problemContent);
        problem.setProblemImage(problemImg);
        problem.setSequenceNumber(DateUtils.parseDateToStr("yyyyMMddHHmmssSSS",new Date()));
        problem.setCreateTime(new Date());
        problem.setLkUserId(userId);
        problem.setVehicleModel(vehicleModel);
        return AjaxResult.success(lkProblemService.insertLkProblem(problem));
    }
    /**
     * 我的问题反馈列表
     */
    @ApiOperation("我的问题反馈列表")
    @GetMapping("/problemList")
    public AjaxResult problemList()
    {
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        LkProblem q=new LkProblem();
        q.setLkUserId(userId);
        List<LkProblem> problems=lkProblemService.selectLkProblemList(q);
        return AjaxResult.success(problems);
    }

    /**
     * 更换手机号-账号验证
     */
    @ApiOperation("更换手机号-账号验证")
    @PostMapping("/checkAccount")
    public AjaxResult checkAccount(@RequestBody LoginBody loginBody)
    {
        LkUser user = userService.selectUserByPhonenumber(loginBody.getPhonenumber());
        if (StringUtils.isNull(user)){
            throw new BaseException("用户不存在");
        }else if (!SecurityUtils.matchesPassword(loginBody.getPassword(), user.getPassword())){
            throw new BaseException("密码不正确");
        }
        return AjaxResult.success("验证通过");
    }

    /**
     * 更换手机号-账号验证
     */
    @ApiOperation("更换手机号-参数手机号 验证码")
    @PostMapping("/changePhone")
    public AjaxResult changePhone(@RequestBody AccountBo accountBo)
    {
        //获取缓存中的验证码
        String code=redisCache.getCacheObject(accountBo.getPhonenumber());
        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("验证码过期,请重新获取");
        }
        //验证码是否正确
        if (!code.equals(accountBo.getCode())){
            return AjaxResult.error("验证码错误");
        }else {
            //验证成功后从缓存中删除
            redisCache.deleteObject(accountBo.getPhonenumber());
        }
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        //判断该手机号有无被其他用户绑定
        LkUser user1 = userService.selectUserByPhonenumber(accountBo.getPhonenumber());
        if (StringUtils.isNotNull(user1)){
            return AjaxResult.error("该手机号已被注册!");
        }
        LkUser user=userService.selectLkUserById(userId);
        user.setPhonenumber(accountBo.getPhonenumber());
        return AjaxResult.success(userService.updateLkUser(user));
    }

    /**
     * 找回密码
     */
    @ApiOperation("找回密码-参数手机号 验证码 密码")
    @PostMapping("/findPassword")
    public AjaxResult findPassword(@RequestBody AccountBo accountBo)
    {
        //获取缓存中的验证码
        String code=redisCache.getCacheObject(accountBo.getPhonenumber());
        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("验证码过期,请重新获取");
        }
        //验证码是否正确
        if (!code.equals(accountBo.getCode())){
            return AjaxResult.error("验证码错误");
        }else {
            //验证成功后从缓存中删除
            redisCache.deleteObject(accountBo.getPhonenumber());
        }
        LkUser user = userService.selectUserByPhonenumber(accountBo.getPhonenumber());
        if (StringUtils.isNull(user)){
            throw new BaseException("用户不存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(accountBo.getPassword()));
        return AjaxResult.success(userService.updateLkUser(user));
    }
    /**
     * 修改密码
     */

    @ApiOperation("修改密码-参数密码 新密码")
    @PostMapping("/updatePassword")
    public AjaxResult updatePassword(@RequestBody AccountBo accountBo)
    {
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        LkUser user=userService.selectLkUserById(userId);
        //验证旧密码
        if (!SecurityUtils.matchesPassword(accountBo.getPassword(), user.getPassword())){
            throw new BaseException("旧密码不正确");
        }
        user.setPassword(SecurityUtils.encryptPassword(accountBo.getNewPassword()));
        return AjaxResult.success(userService.updateLkUser(user));
    }

    /**
     * 更改头像
     */
    @ApiOperation("修改头像")
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarFile") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
            LkUser user=userService.selectLkUserById(userId);
            String avatar = FileUploadUtils.upload(LuKeConfig.getAvatarPath(), file);
            user.setAvatar(avatar);
            userService.updateLkUser(user);
            AjaxResult result=AjaxResult.success();
            result.put("data",avatar);
            return result;
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 修改个人信息
     */
    @ApiOperation("修改个人信息-参数蓝牙设备号、住址、生日、姓名、性别")
    @PostMapping("/updateUserInfo")
    public AjaxResult updateUserInfo(@RequestBody UserBo userBo)
    {

        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        LkUser lkUser=userService.selectLkUserById(userId);
        if(StringUtils.isNotBlank(userBo.getDeviceNumber())){
            lkUser.setDeviceNumber(userBo.getDeviceNumber());
        }
        if(StringUtils.isNotBlank(userBo.getAddress())){
            lkUser.setAddress(userBo.getAddress());
        }
        if(userBo.getBirthday()!=null){
            lkUser.setBirthday(userBo.getBirthday());
        }
        if(StringUtils.isNotBlank(userBo.getNickName())){
            lkUser.setNickName(userBo.getNickName());
        }
        if(StringUtils.isNotBlank(userBo.getSex())){
            lkUser.setSex(userBo.getSex());
        }
        return toAjax(userService.updateLkUser(lkUser));
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @ApiOperation("数据字典：电池类型battery_type,电池电压battery_voltage")
    @GetMapping(value = "/getDicts")
    public AjaxResult getDicts(String dictType)
    {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return AjaxResult.success(data);
    }

    //查询设备报警信息
    @ApiOperation("查询设备报警信息")
    @GetMapping("/retrieveAlarm")
    public AjaxResult retrieveAlarm()
    {
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        LkUser u=userService.selectLkUserById(userId);
        List<Long> userIdList=new ArrayList<>();
        userIdList.add(userId);
        if(u.getParentId().longValue() != 0){
            LkUser user = userService.selectLkUserById(u.getParentId());
            userIdList.add(user.getUserId());
        }
        //通过userId查询报警信息
        List<RetrieveAlarm> alarmList=retrieveAlarmService.selectRetrieveAlarmListByUserIds(userIdList);
        return AjaxResult.success(alarmList);
    }
    //查询设备报警信息
    @ApiOperation("报警信息已读")
    @GetMapping("/alarmRead")
    public AjaxResult alarmRead(Long alarmId)
    {
        return toAjax(retrieveAlarmService.alarmRead(alarmId));
    }

    //查询设备报警信息
    @ApiOperation("查询系统公告")
    @GetMapping("/getSysNotice")
    public AjaxResult getSysNotice()
    {
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        List<SysNotice> noticeList=noticeService.selectNoticeListByUserId(userId);
        return AjaxResult.success(noticeList);
    }
    //查询设备报警信息
    @ApiOperation("系统公告已读")
    @GetMapping("/noticeRead")
    public AjaxResult noticeRead(Long noticeId)
    {
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        return toAjax(noticeService.noticeRead(noticeId,userId));
    }

}


